package com.yuyunbo.hbase.util;

import com.yuyunbo.hbase.annotation.HbRowKey;
import com.yuyunbo.hbase.annotation.HbTableName;
import com.yuyunbo.hbase.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * @Author: yuyunbo-1154363414@qq.com
 * @Date: 2020/5/13 15:56
 * @Description:
 */
public class HbaseAnnotationUtil {

    private static Logger log = LoggerFactory.getLogger(HbaseAnnotationUtil.class);

    public static <T> String getHbaseTbCoRkValue(T dataBean) {
        Class<? extends Object> dataBeanClass = dataBean.getClass();
        HbTableName annotation = dataBeanClass.getAnnotation(HbTableName.class);
        if (annotation != null) {
            String tableName = annotation.tableName();
            String columnFamily = annotation.columnFamily();
            if(StringUtils.isEmpty(tableName) || StringUtils.isEmpty(columnFamily)){
                throw  new HbaseException("表名和列族为空");
            }
            String rowKeyvalue = getRowKeyColumnValue(dataBean);
            return tableName + Constants.COMMA+ columnFamily + Constants.COMMA + rowKeyvalue;
        }
        return Constants.EMPTY;
    }

    public static <T> String getRowKeyColumnValue(T dataBean) {
        Field[] supFields = dataBean.getClass().getSuperclass().getDeclaredFields();
        String value = Constants.EMPTY;
        for (Field field : supFields) {
            field.setAccessible(true);
            try {
                HbRowKey column = field.getAnnotation(HbRowKey.class);
                if (column != null) {
                    value = (String) field.get(dataBean);
                    break;
                }
            } catch (Exception e) {
                log.error("获取habse rowKey主键对应,所属字段值异常", e);
            }
        }
        return value;
    }
}
